package javax.xml.bind.annotation.adapters;

public class CollapsedStringAdapter extends XmlAdapter<String, String> {
    public String marshal(String s) {
        return s;
    }

    public String unmarshal(String text) {
        if (text == null) {
            return null;
        }

        int length = text.length();

        int index = 0;

        while (index < length) {
            if (isWhiteSpace(text.charAt(index))) {
                break;
            }

            index++;
        }

        if (index == length) {
            return text;
        }

        StringBuilder result = new StringBuilder(length);

        if (index != 0) {
            for (int i = 0; i < index; i++)
                result.append(text.charAt(i));

            result.append(' ');
        }

        boolean isStrip = true;

        for (int i = index + 1; i < length; i++) {
            char ch = text.charAt(i);
            boolean b = isWhiteSpace(ch);

            if (isStrip && b) {
                continue;
            }

            isStrip = b;

            if (isStrip) {
                result.append(' ');
            } else {
                result.append(ch);
            }
        }

        length = result.length();

        if ((length > 0) && (result.charAt(length - 1) == ' ')) {
            result.setLength(length - 1);
        }

        return result.toString();
    }

    protected static boolean isWhiteSpace(char ch) {
        if (ch > 0x20) {
            return false;
        }

        return (ch == 0x9) || (ch == 0xA) || (ch == 0xD) || (ch == 0x20);
    }
}
